import { DataTypes } from 'sequelize';
import { sequelize } from '../config/database.js';

const Question = sequelize.define('Question', {
  id: {
    type: DataTypes.INTEGER,
    primaryKey: true,
    autoIncrement: true
  },
  user_id: {
    type: DataTypes.INTEGER,
    allowNull: false,
    comment: '用户ID'
  },
  expert_id: {
    type: DataTypes.INTEGER,
    allowNull: false,
    comment: '专家ID'
  },
  question: {
    type: DataTypes.TEXT,
    allowNull: false,
    comment: '用户提出的问题'
  },
  answer: {
    type: DataTypes.TEXT,
    allowNull: true,
    comment: '专家回答'
  },
  preconditions: {
    type: DataTypes.JSON,
    allowNull: true,
    comment: '用户填写的前置条件',
    get() {
      const value = this.getDataValue('preconditions');
      return value ? (typeof value === 'string' ? JSON.parse(value) : value) : {};
    },
    set(value) {
      this.setDataValue('preconditions', value ? JSON.stringify(value) : null);
    }
  },
  rating: {
    type: DataTypes.ENUM('unsatisfied', 'normal', 'satisfied'),
    allowNull: true,
    comment: '用户评分：unsatisfied-不满意，normal-一般，satisfied-满意'
  },
  ai_request_id: {
    type: DataTypes.STRING(100),
    allowNull: true,
    comment: '大模型API返回的request_id'
  },
  user_quota_id: {
    type: DataTypes.INTEGER,
    allowNull: false,
    comment: '扣减的用户额度ID'
  },
  status: {
    type: DataTypes.ENUM('pending', 'answered', 'failed'),
    allowNull: false,
    defaultValue: 'pending',
    comment: '问答状态：pending-处理中，answered-已回答，failed-失败'
  },
  error_message: {
    type: DataTypes.TEXT,
    allowNull: true,
    comment: '错误信息'
  },
  created_at: {
    type: DataTypes.DATE,
    defaultValue: DataTypes.NOW
  },
  updated_at: {
    type: DataTypes.DATE,
    defaultValue: DataTypes.NOW
  }
}, {
  tableName: 'questions',
  timestamps: true,
  createdAt: 'created_at',
  updatedAt: 'updated_at',
  indexes: [
    {
      name: 'idx_questions_user_id',
      fields: ['user_id'],
    },
    {
      name: 'idx_questions_expert_id',
      fields: ['expert_id'],
    },
    {
      name: 'idx_questions_user_quota_id',
      fields: ['user_quota_id'],
    },
    {
      name: 'idx_questions_status',
      fields: ['status'],
    },
    {
      name: 'idx_questions_rating',
      fields: ['rating'],
    },
    {
      name: 'idx_questions_created_at',
      fields: ['created_at'],
    },
  ],
});

// 实例方法
Question.prototype.toJSON = function() {
  const values = { ...this.get() };
  return values;
};

Question.prototype.setAnswer = async function(answer, aiRequestId = null) {
  this.answer = answer;
  this.status = 'answered';
  if (aiRequestId) {
    this.ai_request_id = aiRequestId;
  }
  await this.save();
  return this;
};

Question.prototype.setFailed = async function(errorMessage) {
  this.status = 'failed';
  this.error_message = errorMessage;
  await this.save();
  return this;
};

Question.prototype.setRating = async function(rating) {
  if (!['unsatisfied', 'normal', 'satisfied'].includes(rating)) {
    throw new Error('Invalid rating value');
  }
  this.rating = rating;
  await this.save();
  return this;
};

// 类方法
Question.getUserQuestions = function(userId, options = {}) {
  const { page = 1, limit = 20, expertId, status } = options;
  const where = { user_id: userId };
  
  if (expertId) {
    where.expert_id = expertId;
  }
  
  if (status) {
    where.status = status;
  }
  
  return this.findAndCountAll({
    where,
    include: [
      { 
        association: 'expert', 
        attributes: ['id', 'nickname', 'avatar_url'],
        include: [{ 
          association: 'domain', 
          attributes: ['id', 'name'] 
        }]
      },
      { association: 'quota', attributes: ['id', 'quota_type'] }
    ],
    order: [['created_at', 'DESC']],
    limit,
    offset: (page - 1) * limit
  });
};

Question.getExpertQuestions = function(expertId, options = {}) {
  const { page = 1, limit = 20, status, rating } = options;
  const where = { expert_id: expertId };
  
  if (status) {
    where.status = status;
  }
  
  if (rating) {
    where.rating = rating;
  }
  
  return this.findAndCountAll({
    where,
    include: [
      { association: 'user', attributes: ['id', 'phone'] },
      { association: 'quota', attributes: ['id', 'quota_type'] }
    ],
    order: [['created_at', 'DESC']],
    limit,
    offset: (page - 1) * limit
  });
};

Question.createQuestion = async function(questionData) {
  return await this.create(questionData);
};

Question.getStatistics = async function(options = {}) {
  const { startDate, endDate, expertId, userId } = options;
  const where = {};
  
  if (startDate && endDate) {
    where.created_at = {
      [sequelize.Sequelize.Op.between]: [startDate, endDate]
    };
  }
  
  if (expertId) {
    where.expert_id = expertId;
  }
  
  if (userId) {
    where.user_id = userId;
  }
  
  const [total, answered, ratings] = await Promise.all([
    this.count({ where }),
    this.count({ where: { ...where, status: 'answered' } }),
    this.findAll({
      where: { ...where, rating: { [sequelize.Sequelize.Op.not]: null } },
      attributes: [
        'rating',
        [sequelize.fn('COUNT', sequelize.col('rating')), 'count']
      ],
      group: ['rating']
    })
  ]);
  
  return {
    total,
    answered,
    ratings: ratings.reduce((acc, item) => {
      acc[item.rating] = parseInt(item.get('count'));
      return acc;
    }, {})
  };
};

export default Question;
